import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login/index.vue')
  },
  {
    path: '/regist',
    name: 'regist',
    component: () => import(/* webpackChunkName: "regist" */ '@/views/regist/index.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home/index.vue'),
  },
  {
    path: '/',
    redirect: '/home'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  // 白名单  不需要token就可以访问你的页面
  const whiteList = ['/login', '/regist']
  if(token) {
    // 说明已经你登录了
    // 不可以跳转白名单页面  直接重定向到首页
    if(whiteList.includes(to.path)) {
      // 拦截到首页
      next('/home')
    } else {
      // 正常跳转
      next()
    }
  } else {
    // 没有token => 没有登录
    if(whiteList.includes(to.path)) {
      next()
    } else {
      // 不是登录或者注册页面
      // 拦截去登录
      next('/login')
    }
  }

  
})

export default router
